<template>
  <el-tabs class="stock" v-model="activeName">
    <el-tab-pane class="secondPage" label="导入数据管理" name="second">
      <div class="select-group">
        <div class="items">
          <span class="items-text">导入时间 : </span>
          <el-date-picker
            v-model="inListQuery.timeValue"
            type="datetimerange"
            value-format='yyyy-MM-dd HH:mm:ss'
            :picker-options="timeOption"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            align="left">
          </el-date-picker>
        </div>
      </div>
      <div class="select-group">
        <div class="items">
          <span class="items-text">文件搜索 : </span>
          <el-input
            placeholder="请输入文件名"
            v-model="inListQuery.fileName">
            <i slot="prefix" class="el-input__icon el-icon-search"></i>
          </el-input>
          <el-button @click="getInList" size="medium" v-waves type="success" class="el-icon-search"><span style="padding-left:5px;">查询</span></el-button>
        </div>
      </div>
      <h4>导入数据列表</h4>
      <el-table empty-text="暂无任何数据信息" :row-class-name="rowClassName" :data="inList" v-loading.body="inListLoading" border fit style="width: 100%">
        <el-table-column align="center" label="文件名" >
          <template slot-scope="scope">
            <span>{{scope.row.fileName}}</span>
          </template>
        </el-table-column>
        <el-table-column align="center" label="导入时间">
          <template slot-scope="scope">
            <span>{{scope.row.time}}</span>
          </template>
        </el-table-column>
        <el-table-column align="center" label="已分配条数 / 总导入条数">
          <template slot-scope="scope">
            <span>{{ scope.row.allotCount + ' / ' + scope.row.count }}</span>
          </template>
        </el-table-column>

        <el-table-column align="center" label="操作" width="320">
          <template slot-scope="scope">
            <router-link @click.native="saveLocal(scope.row,'AD_FILE')" style="margin-right: 9px;" :to="{path:'/dataStock/file'}">
              <el-button type="primary" size="small" icon="el-icon-document">明细</el-button>
            </router-link>
            <el-button @click="openEvent(scope.row,scope.$index)" type="warning" size="small" icon="el-icon-circle-close-outline">{{ scope.row.enable === 1 ? '锁定' : '解锁' }}</el-button>
            <el-button @click="deleteFile(scope.row)" type="danger" size="small" icon="el-icon-delete">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <div v-show="!inListLoading" class="pagination-container">
        <el-pagination background @size-change="inHandleSizeChange" prev-text="上一页" next-text="下一页" @current-change="inHandleCurrentChange" :current-page.sync="inListQuery.current"
                       :page-sizes="[10,20,30,50]" :page-size="inListQuery.pagesize" layout="total, sizes, prev, pager, next, jumper" :total="inTotal">
        </el-pagination>
      </div>

      <el-dialog
        :visible.sync="deleteVisible"
        width="30%"
      >
        <el-alert
          title=" 确认删除该文件？"
          type="warning"
          show-icon
          :closable="false"
        >
        </el-alert>
        <span slot="footer" class="dialog-footer">
        <el-button @click="deleteVisible = false">取 消</el-button>
        <el-button type="primary" @click="deleteData">确 定</el-button>
      </span>
      </el-dialog>

      <el-dialog
        :visible.sync="dialogVisible"
        width="30%"
        @open="setCurrentDialogText"
        @click="dialogVisible = false"
      >
        <el-alert
          :title="currentText"
          type="warning"
          show-icon
          :closable="false"
        >
        </el-alert>
        <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="enableFile">确 定</el-button>
      </span>
      </el-dialog>

    </el-tab-pane>
    <el-tab-pane label="数据库存表" name="first">
      <div class="select-group">
        <div class="items">
          <span class="items-text">所属公司</span>
          <el-select v-model="listQuery.companyId" clearable filterable placeholder="请选择">
            <el-option
              v-for="item in companyArr"
              :key="item.companyId"
              :label="item.companyName"
              :value="item.companyId">
            </el-option>
          </el-select>
        </div>
        <div class="items">
          <span class="items-text">行业</span>
          <el-select v-model="listQuery.industryId" clearable filterable placeholder="请选择">
            <el-option
              v-for="item in industry"
              :key="item.industryId"
              :label="item.industryName"
              :value="item.industryId">
            </el-option>
          </el-select>
        </div>
      </div>
      <div class="select-group">
        <div class="items">
          <span class="items-text">关键词</span>
          <el-select v-model="listQuery.keyword"
          clearable
          filterable
          remote
          :remote-method="key_remoteMethod"
          :loading="keyLoading"
          placeholder="请选择">
          <el-option
            v-for="(item,idx) in keyword"
            :key="idx"
            :label="item"
            :value="item">
          </el-option>
        </el-select>
        </div>
      </div>
      <div class="select-group">
        <div class="items">
          <span class="items-text">系统标签</span>
          <el-select
          v-model="listQuery.sysLabel"
          clearable
          reserve-keyword
          filterable
          remote
          :remote-method="sys_remoteMethod"
          :loading="sysLoading"
          placeholder="请选择">
          <el-option
            v-for="(item,idx) in systemlabel"
            :key="idx"
            :label="item"
            :value="item">
          </el-option>
        </el-select>
        </div>
        <div class="items">
          <span class="items-text">号码归属地</span>
          <el-cascader
            filterable
            clearable
            change-on-select
            :options="areaList"
            v-model="listQuery.areaOptions">
          </el-cascader>
        </div>
        <el-button :disabled="listLoading" @click="getList" size="medium" v-waves type="success" class="el-icon-search">
          <span style="padding-left:5px;">查询</span>
        </el-button>
      </div>
      <h4>数据库存列表</h4>
      <el-table empty-text="暂无任何数据信息" :data="list" v-loading.body="listLoading" border fit style="width: 100%">
        <el-table-column align="center" label="客户ID" >
          <template slot-scope="scope">
            <span>{{!!scope.row.customerName ? scope.row.customerName : '-'}}</span>
          </template>
        </el-table-column>

        <el-table-column align="center" label="所属公司">
          <template slot-scope="scope">
            <span>{{!!scope.row.companyName ? scope.row.companyName : '-'}}</span>
          </template>
        </el-table-column>

        <el-table-column align="center" label="行业">
          <template slot-scope="scope">
            <span>{{scope.row.industryName}}</span>
          </template>
        </el-table-column>

        <el-table-column align="center" label="关键词">
          <template slot-scope="scope">
            <span>{{!!scope.row.keyword ? scope.row.keyword : '-' }}</span>
          </template>
        </el-table-column>

        <el-table-column align="center" label="系统标签">
          <template slot-scope="scope">
            <span>{{ !!scope.row.sysLabel ? scope.row.sysLabel : '-' }}</span>
          </template>
        </el-table-column>

        <el-table-column align="center" label="号码归属地">
          <template slot-scope="scope">
            <span>{{ scope.row.provinceName + ( !scope.row.cityName || scope.row.cityName === '' ? '' :  '/' + scope.row.cityName ) }}</span>
          </template>
        </el-table-column>

        <el-table-column align="center" label="当前虚拟号">
          <template slot-scope="scope">
            <span>{{ scope.row.virtualNumber }}</span>
          </template>
        </el-table-column>

        <el-table-column align="center" label="有效时间">
          <template slot-scope="scope">
            <span>{{ scope.row.lifeTime }}</span>
          </template>
        </el-table-column>

        <el-table-column align="center" label="导入时间">
          <template slot-scope="scope">
            <span>{{ scope.row.insertTime }}</span>
          </template>
        </el-table-column>

        <el-table-column align="center" width="50" label="拨打次数">
          <template slot-scope="scope">
            <span>{{ !!scope.row.callCount ? scope.row.callCount : '0' }}</span>
          </template>
        </el-table-column>

        <el-table-column align="center" label="操作" width="150">
          <template slot-scope="scope">
            <router-link @click.native="saveLocal(scope.row,'AD_COUSTOMER')" :to="{path:'/dataStock/details',query:{id:scope.row.customerId}}">
              <el-button type="primary" size="small" icon="el-icon-document">详情</el-button>
            </router-link>
          </template>
        </el-table-column>
      </el-table>
      <div v-show="!listLoading" class="pagination-container">
        <el-pagination background @size-change="handleSizeChange" prev-text="上一页" next-text="下一页" @current-change="handleCurrentChange" :current-page.sync="listQuery.current"
                       :page-sizes="[10,20,30,50]" :page-size="listQuery.pagesize" layout="total, sizes, prev, pager, next, jumper" :total="total">
        </el-pagination>
      </div>
    </el-tab-pane>
  </el-tabs>
</template>
<script>
import { getIndustryList } from "@/api/user"; //获取行业信息
import {
  getCompany,
  getKeyword,
  getSyslabel,
  getAreaList,
  getCustomerList,
  getImportList,
  enableFile,
  deleteFile
} from "@/api/dataStock";
import waves from "@/directive/waves"; // 水波纹指令

const timeOptions = {
  shortcuts: [
    {
      text: "最近一周",
      onClick(picker) {
        const end = new Date();
        const start = new Date();
        start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
        picker.$emit("pick", [start, end]);
      }
    },
    {
      text: "最近一个月",
      onClick(picker) {
        const end = new Date();
        const start = new Date();
        start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
        picker.$emit("pick", [start, end]);
      }
    },
    {
      text: "最近三个月",
      onClick(picker) {
        const end = new Date();
        const start = new Date();
        start.setTime(start.getTime() - 3600 * 1000 * 24 * 90);
        picker.$emit("pick", [start, end]);
      }
    }
  ]
};

export default {
  name: "user-comp",
  directives: {
    waves
  },
  data() {
    return {
      sysLoading: false,
      keyLoading: false,
      deleteVisible: false,
      currentFileId: "",
      currentItem: null,
      currentIndex: null,
      dialogVisible: false,
      currentText: "",
      areaList: [],
      companyArr: [],
      industry: [],
      keyword: [],
      systemlabel: [],
      activeName: "second",
      infoFormVisible: false,
      formLabelWidth: "120px",
      list: [],
      total: 0,
      listLoading: true,
      listQuery: {
        current: 1,
        pagesize: 10,
        companyId: "",
        industryId: "",
        areaOptions: [],
        keyword: "",
        sysLabel: ""
      },
      inList: [],
      inTotal: 0,
      inListLoading: true,
      inListQuery: {
        current: 1,
        pagesize: 10,
        timeValue: null,
        fileName: ""
      },
      timeOption: timeOptions
    };
  },
  created() {
    this.getList();
    this.getInList();
    this.getOptions();
  },
  beforeRouteEnter(to, from, next) {
    next(vm => {
      vm.$data.activeName = "second";
      // 通过 `vm` 访问组件实例
      getCompany()
        .then(res => {
          vm.$data.companyArr = res.data.info;
        })
        .catch(res => {
          vm.$message.error(res);
        });
    });
  },
  methods: {
    getInList() {
      this.inListLoading = true;
      let tempObj = Object.assign({}, this.inListQuery);
      for (var k in tempObj) {
        if (k === "timeValue") {
          if (tempObj[k] && tempObj[k].length) {
            tempObj["startTime"] = tempObj[k][0];
            tempObj["endTime"] = tempObj[k][1];
          }
          delete tempObj[k];
        } else {
          tempObj[k] === "" ? delete tempObj[k] : null;
        }
      }
      getImportList(tempObj)
        .then(response => {
          const temp = response.data;
          this.inTotal = temp.total;
          this.inList = temp.info;
          this.inListLoading = false;
        })
        .catch(res => {
          this.inListLoading = false;
          this.$message.error(res);
        });
    },
    getList() {
      this.listLoading = true;
      let tempObj = Object.assign({}, this.listQuery);
      for (var k in tempObj) {
        if (k === "areaOptions") {
          if (tempObj[k].length) {
            tempObj["provinceId"] = tempObj[k][0];
            if (tempObj[k].length > 1) {
              tempObj["cityId"] = tempObj[k][1];
            }
            delete tempObj[k];
          } else {
            delete tempObj[k];
          }
        } else {
          tempObj[k] === "" ? delete tempObj[k] : null;
        }
      }
      getCustomerList(tempObj)
        .then(response => {
          const temp = response.data;
          this.total = temp.total;
          this.list = temp.info;
          this.listLoading = false;
        })
        .catch(res => {
          this.listLoading = false;
          this.$message.error(res);
        });
    },
    getOptions() {
      getIndustryList()
        .then(res => {
          let temp = res.data.info;
          this.industry = temp;
        })
        .catch(res => {
          this.$message.error(res);
        });
      getCompany()
        .then(res => {
          let temp = res.data.info;
          this.companyArr = temp;
        })
        .catch(res => {
          this.$message.error(res);
        });
      getAreaList()
        .then(res => {
          let temp = res.data.area;
          this.areaList = temp;
        })
        .catch(res => {
          this.$message.error(res);
        });
    },
    sys_remoteMethod(query) {
      if (query !== "") {
        this.sysLoading = true;
        getSyslabel(query)
          .then(res => {
            this.sysLoading = false;
            let temp = res.data.sysLabel;
            this.systemlabel = temp;
          })
          .catch(res => {
            this.sysLoading = false;
            this.$message.error(res);
          });
      }
    },
    key_remoteMethod(query) {
      if (query !== "") {
        this.keyLoading = true;
        getKeyword(query)
          .then(res => {
            this.keyLoading = false;
            let temp = res.data.keyword;
            this.keyword = temp;
          })
          .catch(res => {
            this.keyLoading = false;
            this.$message.error(res);
          });
      }
    },
    handleSizeChange(val) {
      this.listQuery.pagesize = val;
      this.getList();
    },
    handleCurrentChange(val) {
      this.listQuery.current = val;
      this.getList();
    },
    inHandleSizeChange(val) {
      this.inListQuery.pagesize = val;
      this.getInList();
    },
    inHandleCurrentChange(val) {
      this.inListQuery.current = val;
      this.getInList();
    },
    cancledialog(userForm) {
      //重置表单
      this.$refs[userForm].resetFields();
    },
    openEvent(val, index) {
      this.dialogVisible = true;
      this.currentItem = val;
      this.currentIndex = index;
    },
    setCurrentDialogText() {
      let text = this.currentItem.enable === 1 ? "锁定" : "解锁";
      this.currentText = "您确认要" + text + "该文件 ?";
    },
    enableFile(val, index) {
      let thisEnable = this.currentItem.enable === 1 ? 2 : 1;
      let isInside = this.activeName === "first" ? false : true;
      let thisFileId = this.currentItem.fileId;
      let tempText = thisEnable === 2 ? "锁定" : "解锁";
      enableFile({ fileId: thisFileId, enable: thisEnable })
        .then(res => {
          this.inList[this.currentIndex].enable = thisEnable;
          this.dialogVisible = false;
          this.$message.success(tempText + "成功");
        })
        .catch(res => {
          this.dialogVisible = false;
          this.$message.error(tempText + "失败 " + res);
        });
    },
    deleteData() {
      deleteFile({ fileId: this.currentFileId })
        .then(res => {
          this.deleteVisible = false;
          this.$message.success("删除成功");
          this.getInList(); //重新请求数据
        })
        .catch(res => {
          this.deleteVisible = false;
          this.$message.error("删除失败 " + res);
        });
    },
    deleteFile(item) {
      this.currentFileId = item.fileId;
      this.deleteVisible = true;
    },
    rowClassName({ row, rowIndex }) {
      if (row.enable === 2) {
        return "warning-row";
      }
      return "";
    },
    saveLocal(item, str) {
      // 'AD_COUSTOMER' ; 'AD_FILE'
      let local_user = localStorage.getItem(str);
      !!local_user ? localStorage.removeItem(str) : null;
      localStorage.setItem(str, JSON.stringify(item));
    }
  }
};
</script>

<style type="text/scss" lang="scss" scoped>
.stock {
  .el-alert--warning {
    background-color: #fff;
  }
  .info-item {
    margin: 15px 0px 15px 50px;
    > div {
      display: inline-block;
      min-width: 250px;
    }
    .tipText {
      display: inline-block;
      margin-right: 10px;
      min-width: 100px;
      text-align: right;
    }
  }
  .secondPage .items {
    width: 800px;
    display: inline-block;
    .el-input {
      width: 270px;
      margin-right: 40px;
    }
  }
}
</style>
